package com.tarena.test.rabbitmq.direct;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import org.junit.Before;
import org.junit.Test;

//使用directMode测试路由模式
public class DirectMode {
    private Channel channel;
    @Before
    public void initChannel() throws IOException, TimeoutException {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");
        Connection connection= factory.newConnection();
        channel=connection.createChannel();
    }

    //声明组件 包括交换机 队列 和绑定关系

    @Test
    public void declareComponent() throws IOException{
        //声明队列 声明2个
        channel.queueDeclare("dir-q1", true, false, false, null);
        channel.queueDeclare("dir-q2", true, false, false, null);
        //声明一个路由类型的交换机
        //1.交换机名称 自定义字符串
        //2.交换机类型 direct fanout topic
        channel.exchangeDeclare("dir-exchange", "direct");
        //将队列 dir-q1 使用北京路由key值绑定到交换机 dir-q2使用上海路由key值绑定交换机
        //1.绑定队列
        //2.绑定交换机
        //3.路由key
        channel.queueBind("dir-q1","dir-exchange","北京");
        channel.queueBind("dir-q2","dir-exchange","上海");
    }

    //生成不同的消息 携带不同的key值
    @Test
    public void sendMessage() throws IOException{
        //明确了 消费发给的交换机是谁 dir-exchange
        channel.basicPublish("dir-exchange","北京",null,"hello dir-q1".getBytes());
        channel.basicPublish("dir-exchange","上海",null,"hello dir-q2".getBytes());
    }
}
